<?php

namespace app\index\dao;

use app\common\model\AccountBill;
use ShidianUtil\Thinkphp\Dao\DaoTrait;

/**
 * AccountBillDao 数据访问对象
 * Class AccountBillDao
 * @package app\index\dao
 * @method AccountBill findByPK(?int $id, $field = true)
 * @method \think\Collection selectAll(?int $page, ?int $page_size, $field = true)
 * @method AccountBill insertActive(array $params, array $allow_field = [])
 * @method AccountBill updateActive(AccountBill $model, array $params, array $allow_field = [])
 * @method AccountBill findAndUpdateActive(int $id, array $params, array $allow_field = [])
 * @method AccountBill updateActiveByClosure(\Closure $closure, array $params, array $allow_field = [])
 * @method void deleteModel(AccountBill $model)
 * @method void deleteById(int|array|\Closure $id, bool $force = false)
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class AccountBillDao
{
    use DaoTrait;

    /**
     * @var AccountBill
     */
    private $baseModel;

    /**
     * AccountBillDao constructor.
     */
    public function __construct()
    {
        $this->baseModel = AccountBill::class;
    }

    public function selectBills($memberId, $isIncome, $page, $page_size)
    {
        $query = AccountBill::whereIn('accountType', [PAYMENT_ACCOUNT, PAYMENT_CARD, PAYMENT_COIN]);

        if ($isIncome == 0) {
            // 全部
            $query->where(fn($query) => $query->whereOr(fn($query) => $query->where('fromMemberId', $memberId)->where('fromType', 'member'))
                ->whereOr(fn($query) => $query->where('toMemberId', $memberId)->where('toType', 'member')));
        } elseif ($isIncome == 1) {
            // 收益
            $query->where('toMemberId', $memberId)->where('toType', 'member');
        } elseif ($isIncome == 2) {
            // 支出
            $query->where('fromMemberId', $memberId)->where('fromType', 'member');
        }

        return $query->withAttr([
            'money' => function ($value, $data) {
                $accountType = $data['accountType'] ?? null;
                if ($accountType == PAYMENT_CARD || $accountType == PAYMENT_COIN) {
                    $value = (float)$value;
                }
                return $value;
            }
        ])->append(['iconImg'])
            ->order('id', 'DESC')
            ->order('created', 'DESC')
            ->paging($page, $page_size)
            ->select();
    }
}
